//原生ajax封装成promise
function ajax(method, targetURL, params) {
  this.state = 'FULFILLED'
  this.fulfillList = []
  this.rejectList = []
  var url = baseURL + targetURL
  if(!params) {
    params = ''
  }
  ;(function(that) {
    var data = null
    method = method.toUpperCase()
    if (typeof params == 'object') {
      var _arr = []
      for (var item in params) {
        _arr.push(item + '=' + params[item])
      }
      params = _arr.join('&')
    }
    if (method === 'GET' && params) {
      url += '?' + params
    }
    if (method === 'POST') {
      data = params
    }
    //start
    var xhr = new XMLHttpRequest()
    xhr.open(method, url)
    xhr.setRequestHeader('Content-type', 'appliction/x-www-form-urlencoded')
    xhr.addEventListener('readystatechange', function() {
      if (this.readyState !== 4) return
      if (this.status !== 200)
        reject({status: this.status, statusText: this.statusText})
      else resolve(this.responseText)
    })
    xhr.send(data)
    //成功
    var resolve = function(data) {
      that.state = 'FULFILLED'
      setTimeout(function() {
        that.fulfillList.forEach(function(itemFn, key, arr) {
          itemFn(data)
          arr.shift()
        })
      }, 0)
    }
    //失败，执行失败队列的函数
    var reject = function(data) {
      that.state = 'REJECTED'
      setTimeout(function() {
        that.rejectList.forEach(function(itemFn, key, arr) {
          itemFn(data)
          arr.shift()
        })
      }, 0)
    }
  })(this)
}
//成功回调函数
ajax.prototype.done = function(handle) {
  if (typeof handle === 'function') this.fulfillList.push(handle)
  else throw new Error('回调函数出错')
  return this
}
//失败回调函数
ajax.prototype.fail = function(handle) {
  if (typeof handle === 'function') this.rejectList.push(handle)
  else throw new Error('回调函数出错')
  return this
}
//失败成功写在一个方法内
ajax.prototype.then = function(fulfill, reject) {
  this.done(fulfill || function() {}).fail(reject || function(res) {
    addMessage(res,'warning')
  })
  return this
}
